package com.conn3cted.phrasebook.domain;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import java.util.Date;
import java.util.List;
import java.util.Set;

import com.conn3cted.phrasebook.domain.Person;

import java.util.HashSet;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.CascadeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

@Configurable
@Entity
public class Phrase {

    @NotNull
    @Size(max = 500)
    private String title;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    private Date created;
    
    private int votes;

    @OneToMany(cascade = CascadeType.ALL)
    private Set<Person> votedBy = new HashSet<Person>();

    public Phrase() {
    	created = new Date();
    }
    
	public Phrase(String string, long id, long time) {
		title = string;
		this.id = id;
		created = new Date(time);
	}

	public String getTitle() {
        return this.title;
    }

	public void setTitle(String title) {
        this.title = title;
    }

	public int getVotes() {
        return this.votes;
    }

	public void setVotes(int votes) {
        this.votes = votes;
    }

	public Set<Person> getVotedBy() {
        return this.votedBy;
    }

	public void setVotedBy(Set<Person> votedBy) {
        this.votedBy = votedBy;
    }
	
	public Date getCreated() {
		return created;
	}

	public void setCreated(Date created) {
		this.created = created;
	}

	@PersistenceContext
    transient EntityManager entityManager;

	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

	@Version
    @Column(name = "version")
    private Integer version;

	public Long getId() {
        return this.id;
    }

	public void setId(Long id) {
        this.id = id;
    }

	public Integer getVersion() {
        return this.version;
    }

	public void setVersion(Integer version) {
        this.version = version;
    }

	@Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

	@Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Phrase attached = Phrase.findPhrase(this.id);
            this.entityManager.remove(attached);
        }
    }

	@Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

	@Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

	@Transactional
    public Phrase merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Phrase merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

	public static final EntityManager entityManager() {
        EntityManager em = new Phrase().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

	public static long countPhrases() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Phrase o", Long.class).getSingleResult();
    }

	public static List<Phrase> findAllPhrases() {
        return entityManager().createQuery("SELECT o FROM Phrase o", Phrase.class).getResultList();
    }

	public static Phrase findPhrase(Long id) {
        if (id == null) return null;
        return entityManager().find(Phrase.class, id);
    }

	public static List<Phrase> findPhraseEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Phrase o", Phrase.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

	public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Id: ").append(getId()).append(", ");
        sb.append("Title: ").append(getTitle()).append(", ");
        sb.append("Version: ").append(getVersion()).append(", ");
        sb.append("VotedBy: ").append(getVotedBy() == null ? "null" : getVotedBy().size()).append(", ");
        sb.append("Votes: ").append(getVotes());
        return sb.toString();
    }

	
}
